package app;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTabHost;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.cyan.tools.util.RxBus;
import com.example.menhoo.toollibrary.common.assist.Check;
import com.example.menhoo.toollibrary.common.helper.DateUtil;
import com.example.menhoo.toollibrary.common.helper.ExitAppUtil;
import com.example.menhoo.toollibrary.common.utils.AndroidUtil;
import com.example.menhoo.toollibrary.common.utils.HandlerUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.bitmap.BitmapDisplayConfig;
import com.lidroid.xutils.bitmap.callback.BitmapLoadCallBack;
import com.lidroid.xutils.bitmap.callback.BitmapLoadFrom;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.util.LogUtils;
import com.socks.library.KLog;
import com.zejian.emotionkeyboard.utils.SharedPreferencedUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import application.AppApplication;
import application.HttpUrlConstant;
import application.KeyConstant;
import bean.DoListNotifySourceBean;
import custom.BadgeView;
import fragment.MY;
import fragment.WebHtml;
import http.OkHttpHelper;
import interfaces.IReturnObject;
import mainUI.AppActivity;
import mainUI.AppFragment;
import menhoo.com.i8officelibrary.R;
import model.IMCvnDBModel;
import model.IMMessageDBModel;
import model.TabModel;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import service.SignalrService;
import tools.ToastUtil;
import utils.SharePreferHelper;
import utils.TipsUtils;
import utils.Utils;

public class Main extends AppActivity implements AppFragment.BackHandledInterface {

    /*
    一个记录变量，为了应对Main执行checkUpdate的时候MY Fragment还没有实例化不能现实new图标，以此做记录
     */
    public static boolean isShowNewVerTip = false;

    List<TabModel> tabList;

    FragmentTabHost mTabHost;

    TabModel currSelect = null;
    int currIndex = -1;
    Date currDate = null;

    List<BadgeView> badgeViewList = new ArrayList();
    String imTitle = null;
    private List<DoListNotifySourceBean.NotifySourcesBean> notifyList;
    OkHttpHelper okHttpHelper = OkHttpHelper.getInstance();
    private int WRITE_EXTERNAL_STORAGE_REQUEST_CODE = 0x0001;
    private MaterialDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setRunSignalrService(true);
        super.onCreate(savedInstanceState);

        //
        setContentView(R.layout.main);
        try {
            mTabHost = (FragmentTabHost) findViewById(R.id.tabhost);
        } catch (Exception e) {
            LogUtils.e(e.getMessage() + "");
        }

        setTitleDisplay(false);
        setIsImHint(true);
        init();
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            //申请WRITE_EXTERNAL_STORAGE权限
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    WRITE_EXTERNAL_STORAGE_REQUEST_CODE);
        }
        requestAllContact();
    }

    private void requestAllContact() {
        String url = HttpUrlConstant.getWebSiteFullUrl(HttpUrlConstant.AccountAllAndroid_CACHE);
        final String urlF = HttpUrlConstant.getWebSiteFullUrl(url) + "?__session__=" + AppApplication.getSession();
        KLog.e(urlF);
        OkHttpClient client = new OkHttpClient.Builder()
                .readTimeout(60,TimeUnit.SECONDS)
                .writeTimeout(60,TimeUnit.SECONDS)
                .connectTimeout(60,TimeUnit.SECONDS)
                .build();
        Call call = client.newCall(new Request.Builder()
                .url(urlF)
                .get()
                .build());
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // 重新获取
//                requestAllContact();
                ToastUtil.show(Main.this, R.string.network_error);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                if (TextUtils.isEmpty(result)) {
                    return;
                }
                result = Utils.removeAllBlank(result);
                KLog.e(result);
                final String resultCache = SharedPreferencedUtils.getString(Main.this, "contacts");
                if (TextUtils.isEmpty(resultCache) || !resultCache.equals(result)) {
                    SharedPreferencedUtils.setString(Main.this, "contacts", result);
                }
                RxBus.get().post("refreshContact", result);
            }
        });
    }

    /**
     * 根据json数据构建tab
     */
    void init() {
        //激活jpush
//        SharedPreferences sp = AppApplication.getInstance().getSharedPreferences("sp", Context.MODE_PRIVATE);
//        boolean isShow = sp.getBoolean(UIKeyValueSet.IsNotificationOpen, true);
//        if (isShow && JPushInterface.isPushStopped(getApplicationContext()))
//            JPushInterface.resumePush(getApplicationContext());

        tabList = new ArrayList();

        //得到前4个(最多)
//        try {
//            List<TabModel> tabModelList = getDB().findAll(Selector.from(TabModel.class).where("isShow", "=", true).orderBy
//                    ("id", false).limit(4));
//            if (tabModelList != null && tabModelList.size() > 0) {
//                for (TabModel temp : tabModelList) {
//                    tabList.add(temp);
//                }
//            }
//
//        } catch (Exception e) {
//            LogUtils.e(e.getMessage() + "");
//        }

        TabModel tabApp = new TabModel();
        tabApp.code = "Apps";
        tabApp.type = "internal";
        tabApp.name = "应用";
        tabList.add(tabApp);

        TabModel tabContact = new TabModel();
        tabContact.code = "People";
        tabContact.type = "internal";
        tabContact.name = "联系人";
        tabList.add(tabContact);

        TabModel tabMy = new TabModel();
        tabMy.code = "My";
        tabMy.type = "internal";
        tabMy.name = "我";
        tabMy.icon = R.mipmap.my_g48;
        tabMy.icon_sel = R.mipmap.my_r48;
        tabList.add(tabMy);

        for (TabModel model : tabList) {
            if (model.code.equals("news")) {
                model.icon = R.raw.xinxi1;
                model.icon_sel = R.raw.xinxi2;
            } else if (model.code.equals("Apps")) {
                model.name = "应用";
                model.iconUrl = "";
                model.icon = R.mipmap.ic_apps_uncheck;
                model.icon_sel = R.mipmap.ic_apps_check;
            } else if (model.code.equals("People")) {
                model.name = "通讯录";
                model.iconUrl = "";
                model.icon = R.mipmap.ic_people_uncheck;
                model.icon_sel = R.mipmap.ic_people_check;
            }
        }

        setupTabView();

//        getTipNotice();

    }

    /**
     * 获取未读消息数量
     */
//    private void getTipNotice() {
//        TipsUtils.getTabTips(new TipsUtils.onGetTipNumSuccess() {
//            @Override
//            public void setOnGetTipNumSuccess(String AppCode, String num) {
//                showTipNotice(AppCode, num);
//            }
//        });
//        TipsUtils.getIMUnReadTotalNum(new TipsUtils.onGetTipNumSuccess() {
//            @Override
//            public void setOnGetTipNumSuccess(String AppCode, String num) {
//                showTipNotice(AppCode, num);
//            }
//        });
//    }


//    public void getTabTipNum() {
//        String tipListStr = SharePreferHelper.getStrValues("tipList", "");
//
//        Gson gson = new Gson();
//        final List<DoListNotifySourceBean.NotifySourcesBean> tipList = gson.fromJson(tipListStr, new TypeToken<List<DoListNotifySourceBean.NotifySourcesBean>>() {
//        }.getType());
//        if (tipList != null) {
//            for (DoListNotifySourceBean.NotifySourcesBean sourcesBean : tipList) {
//                TipsUtils.getNotifyNum(sourcesBean.getAppCode(), sourcesBean.getNSUrl(), new TipsUtils.onGetTipNumSuccess() {
//                    @Override
//                    public void setOnGetTipNumSuccess(String AppCode, String num) {
//                        showTipNotice(AppCode, num);
//                    }
//                });
//            }
//        }
//
//        TipsUtils.getIMUnReadTotalNum(new TipsUtils.onGetTipNumSuccess() {
//            @Override
//            public void setOnGetTipNumSuccess(String AppCode, String num) {
//                showTipNotice(AppCode, num);
//            }
//        });
//    }


    /**
     * 构建tab
     */
    void setupTabView() {

        mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
        mTabHost.getTabWidget().setDividerDrawable(null);

        int count = tabList.size();

        List<View> ViewList = new ArrayList<>();

        for (int i = 0; i < count; i++) {
            TabModel tab = tabList.get(i);

            View view = getTabItemView(tab);
            ViewList.add(view);
            TabHost.TabSpec tabSpec = mTabHost.newTabSpec(i + "").setIndicator(view);
            Bundle mBundle = new Bundle();


            if (tab.code.equals("Apps")) {
                mBundle.putString("Title", "高新区（新吴区）移动政务");
            } else {
                mBundle.putString("Title", tab.name);
            }

            mBundle.putString("Url", tab.htmlUrl);
            if (tab.type.equalsIgnoreCase("html")) {
                mBundle.putBoolean("IsShowTitle", false);
                mBundle.putBoolean("IsShowBtnBack", false);
                mBundle.putBoolean("IsMainPage", true);
            } else {
                mBundle.putBoolean("IsShowTitle", true);
                mBundle.putBoolean("IsShowBtnBack", false);
            }

            mTabHost.addTab(tabSpec, tab.getFragment(), mBundle);


            final int F_i = i;
            mTabHost.getTabWidget().getChildTabViewAt(i).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    if (currDate != null) {
                        Date secTime = DateUtil.Now();
                        if (currIndex == F_i && secTime.getTime() - currDate.getTime() < 300) {
                            //双击
                            LogUtils.e("双击了" + F_i);
                            if (currSelect != null && currSelect.type.equalsIgnoreCase("html")) {
                                int string_int = tabList.indexOf(currSelect);
                                Fragment fragment = getSupportFragmentManager().findFragmentByTag("" + string_int);
                                if (fragment instanceof WebHtml) {
                                    WebHtml webHtml = (WebHtml) fragment;
                                    webHtml.Reload();
                                }
                            } else {
                                //MessageUtil.showSingletonToast(Main.this, "原生");
                            }

                            currDate = DateUtil.Now();
                        } else {
                            currDate = DateUtil.Now();
                        }
                    } else {
                        currDate = DateUtil.Now();
                    }

                    mTabHost.setCurrentTab(F_i);
                    currSelect = tabList.get(F_i);
                    currIndex = F_i;

                    int index = 0;
                    for (TabModel tm : tabList) {
                        LogUtils.e("TabModel:" + tm.toString());
                        ImageView imageView = (ImageView) mTabHost.getTabWidget().getChildTabViewAt(index).findViewById(R.id.iv_icon);
                        String url = "";
                        imageView.setImageResource(index == F_i ? tm.icon_sel : tm.icon);
                        index++;
                    }

                }
            });
            badgeViewList.add(new BadgeView(this, mTabHost.getTabWidget(), i));
        }
        getSupportFragmentManager().executePendingTransactions();
        //设置最开始选中的
        currSelect = tabList.get(0);

        //
        TabModel firstTM = tabList.get(0);
        if (firstTM != null) {
            ImageView imageView = (ImageView) mTabHost.getTabWidget().getChildTabViewAt(0).findViewById(R.id.iv_icon);
            imageView.setImageResource(firstTM.icon_sel);
        }
    }

    /**
     * 返回tab显示的view
     *
     * @return
     */
    View getTabItemView(TabModel model) {
        LayoutInflater layoutInflater = LayoutInflater.from(this);
        View view = layoutInflater.inflate(R.layout.tab_bottom_nav, null);

        ImageView imageView = (ImageView) view.findViewById(R.id.iv_icon);

        //如果iconUrl不为空就用iconUrl否则就用icon
        if (Check.isEmpty(model.iconUrl)) {
            imageView.setImageResource(model.icon);
        } else {
            getIconLoader().display(imageView, model.iconUrl + "?t=g48", new BitmapLoadCallBack<ImageView>() {
                @Override
                public void onLoadCompleted(ImageView imageView, String s, Bitmap bitmap, BitmapDisplayConfig bitmapDisplayConfig, BitmapLoadFrom bitmapLoadFrom) {
                    imageView.setImageBitmap(bitmap);
                }

                @Override
                public void onLoadFailed(ImageView imageView, String s, Drawable drawable) {
                    imageView.setImageResource(R.drawable.load_failed);
                }
            });

        }

        TextView textView = (TextView) view.findViewById(R.id.tv_icon);
        textView.setText(model.name);

        return view;
    }


    public void showTip(String tabName, String text) {
        for (TabModel tab : tabList) {
            if (tab.name.equalsIgnoreCase(tabName)) {
                int string_int = tabList.indexOf(tab);
                BadgeView badgeView = badgeViewList.get(string_int);

                badgeView.setBadgePosition(BadgeView.POSITION_CENTER);
                if (text.length() == 1) {
                    badgeView.setBadgeMargin(40, -45);
                } else if (text.length() == 2) {
                    badgeView.setBadgeMargin(50, -45);
                } else if (text.length() == 3) {
                    badgeView.setBadgeMargin(60, -45);
                } else {
                    badgeView.setBadgeMargin(60, -45);
                }
                badgeView.setTextSize(12);
                //badgeView.setPadding(4,3,4,4);

                badgeView.setBackgroundResource(R.drawable.corners_red_50dp);
                badgeView.setText(text);
                if (!badgeView.isShown()) {
                    badgeView.show();
                }

                return;
            }
        }

    }

    public void hideTip(String title) {
        for (TabModel tab : tabList) {
            if (tab.name.equalsIgnoreCase(title)) {
                int string_int = tabList.indexOf(tab);
                BadgeView badgeView = badgeViewList.get(string_int);
                badgeView.hide();
                return;
            }
        }
    }

    /**
     * 显示从网络请求来得未读数目
     *
     * @param AppCode
     * @param num
     */
    public void showTipNotice(String AppCode, String num) {
        if (num.equals("0")) {
            hideTipNotice(AppCode);
            return;
        }
        for (TabModel tab : tabList) {
            if (tab.code.contains(AppCode)) {
                int string_int = tabList.indexOf(tab);
                BadgeView badgeView = badgeViewList.get(string_int);

                badgeView.setBadgePosition(BadgeView.POSITION_CENTER);
                if (num.length() == 1) {
                    badgeView.setBadgeMargin(40, -45);
                } else if (num.length() == 2) {
                    badgeView.setBadgeMargin(50, -45);
                } else if (num.length() == 3) {
                    badgeView.setBadgeMargin(60, -45);
                } else {
                    badgeView.setBadgeMargin(60, -45);
                }
                badgeView.setTextSize(12);
                //badgeView.setPadding(4,3,4,4);

                badgeView.setBackgroundResource(R.drawable.corners_red_50dp);
                badgeView.setText(num);
                if (!badgeView.isShown()) {
                    badgeView.show();
                }

                return;
            }
        }

    }

    public void hideTipNotice(String AppCode) {
        for (TabModel tab : tabList) {
            if (tab.name.contains(AppCode)) {
                int string_int = tabList.indexOf(tab);
                BadgeView badgeView = badgeViewList.get(string_int);
                badgeView.hide();
                return;
            }
        }
    }

    public void hideAllTip() {
        for (TabModel tab : tabList) {
            int string_int = tabList.indexOf(tab);
            BadgeView badgeView = badgeViewList.get(string_int);
            badgeView.hide();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
//        refreshIMTip();
//        getTabTipNum();
//        getTipNotice();
//        if (dialog != null && !dialog.isShowing()) {
//            dialog.show();
//        }
    }

    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();
        checkUpdate();
    }

    public void checkUpdate() {
        UploadApp.CheckUpdate(new IReturnObject<String>() {
            @Override
            public void returnResult(String result) {
                try {
                    if (result != null) {

                        JSONObject tempHeightVer = null;
                        final String IsDownloadUpdateTestApk = AppApplication.getAppKeyValueSet().readAppSetPreferences
                                (KeyConstant.IsDownloadUpdateTestApk);
                        final String appName = AppApplication.getAppKeyValueSet().readAppSetPreferences(KeyConstant
                                .AppUniquenessName);
                        LogUtils.e("IsDownloadUpdateTestApk:" + IsDownloadUpdateTestApk);
                        LogUtils.e("appName:" + appName);

                        JSONObject jsonObject = new JSONObject(result);
                        JSONObject appJson = jsonObject.getJSONObject(appName);
                        JSONArray Versions = appJson.getJSONArray("Versions");

                        for (int i = 0; i < Versions.length(); i++) {
                            JSONObject versionJson = Versions.getJSONObject(i);
                            if (!IsDownloadUpdateTestApk.equalsIgnoreCase("true") && versionJson.getString("Type")
                                    .equalsIgnoreCase("T")) {
                                continue;
                            }
                            if (tempHeightVer == null) {
                                tempHeightVer = versionJson;
                            } else {
                                String oldVer = tempHeightVer.getString("Version");
                                String newVer = versionJson.getString("Version");

                                if (!Check.isEmpty(oldVer) && !Check.isEmpty(newVer)) {
                                    if (UploadApp.compareVersion(newVer, oldVer) == 1) {
                                        tempHeightVer = versionJson;
                                    }
                                }
                            }
                        }
                        String currVersion = AndroidUtil.getVerName(Main.this);
                        if (UploadApp.compareVersion(tempHeightVer.getString("Version"), currVersion) == 1) {
                            //进行更新操作
                            final String url = tempHeightVer.getString("Url");
                            final String ver = tempHeightVer.getString("Version");
                            final String note = tempHeightVer.getString("Note");

                            if (AppApplication.isMainUpdateInfo) {
                                //延迟500的意义在于，UploadApp页面正在下载的时候，关闭UploadApp页面执行cancelDownload清除下载命令，这个清除下载是异步的有执行需要一点点时间，延迟500
                                // ，以便cancelDownload执行完毕，开始新的下载
                                HandlerUtil.runOnUiThreadDelay(new Runnable() {
                                    @Override
                                    public void run() {
                                        dialog = new MaterialDialog.Builder(Main.this)
                                                .title("发现新版本:" + ver)
                                                .content(note.replace("\\n", "\n"))
                                                .cancelable(false)
                                                .canceledOnTouchOutside(false)
                                                .positiveText("去更新")
                                                .onPositive(new MaterialDialog.SingleButtonCallback() {
                                                    @Override
                                                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                                        Intent it = new Intent(Main.this, UploadApp.class);
                                                        it.putExtra("url", url);
                                                        it.putExtra("version", ver);
                                                        it.putExtra("version_info", note);
                                                        startActivity(it);
                                                    }
                                                })
                                                .negativeText("取消")
                                                .onNegative(new MaterialDialog.SingleButtonCallback() {
                                                    @Override
                                                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                                        ExitAppUtil.getInstance().exit();
                                                    }
                                                })
                                                .show();


                                    }
                                }, 500);
                            }
//                            HandlerUtil.runOnUiThreadDelay(new Runnable() {
//                                @Override
//                                public void run() {
//                                    setNewVerTipShow(true);
//                                }
//                            }, 200);


                        } else {
                            //提示已经是最新版本
                            setNewVerTipShow(false);
                        }

                    } else {
                        //失败
                        setNewVerTipShow(false);
                    }

                } catch (Exception e) {
                    LogUtils.e(e.getMessage() + "");
                    setNewVerTipShow(false);

                }
            }
        });
    }

    /*
    显示新版本提示
     */
    public void setNewVerTipShow(boolean F) {
        isShowNewVerTip = F;
        if (isShowNewVerTip) {
            showTip("我", "new");
        } else {
            hideTip("我");
        }
        for (TabModel tab : tabList) {
            if (tab.name.equalsIgnoreCase("我")) {
                int string_int = tabList.indexOf(tab);
                try {
                    MY fragment = (MY) getSupportFragmentManager().findFragmentByTag("" + string_int);
                    fragment.setNewVerTipShow(F);
                } catch (Exception e) {
                    LogUtils.e(e.getMessage() + "");
                }

                return;
            }
        }


    }

    public void setIMTipType(String title) {
        this.imTitle = title;
        if (title != null) {
            setIsImHint(false);
        } else {
            setIsImHint(true);
        }
    }

//    public void refreshIMTip() {
//        if (!isImHint) {
//            try {
//                List<IMCvnDBModel> cvnList = getDB().findAll(Selector.from(IMCvnDBModel.class).where("unreadCount", ">", 0).and("CurrUserID", "=", AppApplication
//                        .getUser().EmplID).and("CurrWebSite", "=", HttpUrlConstant.getWebSiteFullUrl("")));
//                if (cvnList != null && cvnList.size() > 0) {
//                    int i = 0;
//                    for (IMCvnDBModel item : cvnList) {
//                        i += item.unreadCount;
//                    }
//                    if (i > 99) {
//                        showTip(this.imTitle, "99+");
//                    } else {
//                        showTip(this.imTitle, i + "");
//                    }
//                } else {
//                    hideTip(this.imTitle);
//                }
//            } catch (Exception e) {
//            }
//        }
//    }

    @Override
    public void OnImMessage(Context context, IMMessageDBModel message) {
        super.OnImMessage(context, message);
//        refreshIMTip();
    }


    private AppFragment mFragment;

    @Override
    public void setSelectedFragment(AppFragment selectedFragment) {
        this.mFragment = selectedFragment;
    }

    @Override
    public void onBackPressed() {
        if (mFragment == null || !mFragment.onBackPressed()) {
            if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
                showSimpleDialogMessage("是否退出 " + getString(R.string.app_name), new IReturnObject() {
                    @Override
                    public void returnResult(Object result) {
                        //网络断开siganalr逻辑代码
                        SignalrService signalr = getSignalrService();
                        if (signalr != null) {
                            signalr.StopSignalr();
                        }
                        HandlerUtil.runOnUiThreadDelay(new Runnable() {
                            @Override
                            public void run() {

                                ExitAppUtil.getInstance().exit();
                            }
                        }, 400);

                    }
                }, true, true);
//                super.onBackPressed();
            } else {
                getSupportFragmentManager().popBackStack();
            }
        }
    }
}
